import React, { useState, useEffect } from 'react';
import { Table, Button, notification, Tree, Menu, Tag } from 'antd';
import SearchList from '@/components/SearchList';
import moment from 'moment';
import { EyeFilled, EditOutlined, DeleteFilled } from '@ant-design/icons';
import API from '@/api/xjindex.js';
import { transFormIndex, showDeleteConfirm } from '@/utils/util';
import { connect, useDispatch, history, useModel } from 'umi';

const safetyInspection = () => {
  const [list, setList] = useState([]);
  const { initialState } = useModel('@@initialState');
  const { userId } = initialState.info;
  const [YZDJList, setYZDJList] = useState([]);
  const [GJFLList, setGJFLList] = useState([]);

  const [pagination, setPagination] = useState({
    showQuickJumper: true,
  });
  const searchList = [
    {
      name: 'alarmTitle',
      title: '告警名称',
      type: 'input',
    },
    {
      name: 'sourceAddress',
      title: '攻击者组',
      type: 'input',
    },
    {
      name: 'destinationAddress',
      title: '受害者组',
      type: 'input',
    },
    // {
    //   name: 'type',
    //   title: '组织属性',
    //   type: 'select',
    //   otherProps: {
    //     options: orgOptions,
    //   },
    // },
  ];

  const treeData = [
    {
      title: '告警等级',
      key: 'severityLevel',
      disabled: true,
      children: YZDJList,
    },
    {
      title: '告警分类',
      key: 'classification',
      disabled: true,
      children: GJFLList,
    },
    {
      title: '处置状态',
      key: 'disposeState',
      disabled: true,
      children: [
        {
          title: '未处置',
          key: '10',
          selectable: false,
        },
        {
          title: '已处置',
          key: '11',
          selectable: false,
        },
        {
          title: '忽略',
          key: '12',
          selectable: false,
        },
      ],
    },
    {
      title: '确认状态',
      key: 'readState',
      disabled: true,
      children: [
        {
          title: '未读',
          key: 5,
          selectable: false,
        },
        {
          title: '已读',
          key: 4,
          selectable: false,
        },
      ],
    },
  ];

  const [params, setParams] = useState({
    alarmTitle: '', //告警标题
    alarmType: '', //告警类型
    alarmLevel: '', //告警等级
    alarmTime: '', //告警时间
    sourceAddress: '', //攻击组
    destinationAddress: '', //受害组
    readState: '', //确认状态
    disposeState: '', //处置状态

    alarmContent: '', //告警内容
    alarmId: '', //告警ID
    threatScore: '', //威胁分值

    pageNo: 1,
    pageSize: 10,
  });

  useEffect(() => {
    API.dictItemYZDJList().then((res) => {
      if (res) {
        setYZDJList(
          res.t.map((item) => {
            return {
              title: item.dictItemName,
              key: item.dictItemType,
              id: item.dictItemType,
              selectable: false,
            };
          }),
        );
      }
    });
    API.dictItemGZFLList().then((res) => {
      if (res) {
        setGJFLList(
          res.t.map((item) => {
            return {
              title: item.dictItemName,
              key: item.dictItemName,
              selectable: false,
            };
          }),
        );
      }
    });
  }, []);

  const initList = (data = {}) => {
    const values = { ...params, ...data };

    API.getAlarm(values).then((res) => {
      if (res?.t) {
        setList(res.t.queryList);
        setPagination({
          ...pagination,
          total: res.t.totalSize,
          current: res.t.currentPage,
          pageSize: res.t.pageSize,
        });
      }
    });
  };

  const changeTable = (pagination) => {
    setParams({
      ...params,
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  const [expandedKeys, setExpandedKeys] = useState([
    'severityLevel',
    'classification',
    'disposeState',
    'readState',
  ]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const onExpand = (expandedKeysValue) => {
    // console.log('onExpand', expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.

    setExpandedKeys(expandedKeysValue);
    // setAutoExpandParent(true);
  };

  const onCheck = (checkedKeysValue) => {
    // console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };

  const clearChecked = () => {
    setCheckedKeys([]);
    // 点击清除时，是否要查询列表
    // params.disposeState = '';
    // params.readState = '';
    // params.alarmLevel = '';
    // params.alarmType = '';
    // initList(params)
  };

  useEffect(() => {
    initList(params);
  }, [params]);
  const searchFn = (data = {}) => {
    if (checkedKeys) {
      params.disposeState = '';
      params.readState = '';
      params.alarmLevel = '';
      params.alarmType = '';
      checkedKeys.map((item) => {
        if (item == '10') {
          params.disposeState += '0,';
        } else if (item == '11') {
          params.disposeState += '1,';
        } else if (item == '12') {
          params.disposeState += '2,';
        } else if (item == 5) {
          params.readState += '0,';
        } else if (item == 4) {
          params.readState += '1,';
        } else if (item == 0 || item == 1 || item == 2 || item == 3) {
          params.alarmLevel = params.alarmLevel + item + ',';
        }
        //  if (
        //   item == '扫描探测' ||
        //   item == '主机异常' ||
        //   item == '异常通信' ||
        //   item == '漏洞攻击' ||
        //   item == '账号异常' ||
        //   item == '运维监控告警' ||
        //   item == '拒绝服务' ||
        //   item == '威胁情报预警' ||
        //   item == '中间人攻击' ||
        //   item == '邮件'
        // )
        else {
          params.alarmType = params.alarmType + item + ',';
        }
      });
    }
    params.alarmTitle = data.alarmTitle || '';
    params.sourceAddress = data.sourceAddress || '';
    params.destinationAddress = data.destinationAddress || '';
    setParams({
      ...params,
      pageNo: 1,
      pageSize: 10,
    });
  };

  const stateMap = {
    0: {
      color: 'gold',
      text: '未处置',
    },
    1: {
      color: 'cyan',
      text: '已处置',
    },
    2: {
      color: 'geekblue',
      text: '忽略',
    },
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'Index',
      align: 'center',
      render: (text, r, index) => transFormIndex(pagination, index),
    },
    {
      title: '告警标题',
      dataIndex: 'alarmTitle',
      align: 'center',
    },
    {
      title: '威胁分值',
      dataIndex: 'threatScore',
      align: 'center',
    },
    {
      title: '告警等级',
      dataIndex: 'alarmLevel',
      align: 'center',
      render: (text) => {
        let a = {};
        YZDJList.forEach((e) => {
          a[e.id] = e.title;
        });
        return a[text];
      },
    },
    {
      title: '攻击者组',
      dataIndex: 'sourceAddress',
      align: 'center',
    },
    {
      title: '受害者组',
      dataIndex: 'destinationAddress',
      align: 'center',
    },
    {
      title: '告警时间',
      dataIndex: 'createTime',
      type: 'dateTimePicker',
      align: 'center',
      render: (val) => <span>{moment(val).format('YYYY-MM-DD')}</span>,
    },
    {
      title: '告警类型',
      dataIndex: 'alarmType',
      align: 'center',
    },
    {
      title: '处置状态',
      dataIndex: 'disposeState',
      align: 'center',
      render: (t) => <Tag color={stateMap[t].color}>{stateMap[t].text}</Tag>,
    },
    {
      title: '确认状态',
      dataIndex: 'readState',
      align: 'center',
      render: (readState) => (
        <Tag color={readState == 0 ? 'red' : 'green'}>
          {readState == 0 ? '未读' : '已读'}
        </Tag>
      ),
    },
    {
      title: '操作',
      dataIndex: 'Operation',
      align: 'center',
      render: (text, r) => (
        // console.log(r),
        <div>
          <Button
            type="link"
            key="detail"
            icon={<EyeFilled />}
            className="table-icon"
            onClick={checkLink.bind(null, r.id)}
          >
            详情
          </Button>
          {r.disposeState == '0' ? ( //处置按钮显示
            <Button
              type="link"
              key="disposal"
              icon={<EditOutlined />}
              className="table-icon"
              onClick={setDisposeLink.bind(null, r.id)}
            >
              处置
            </Button>
          ) : (
            ''
          )}

          {/* <Button
            type="link"
            key='delete'
            icon={<DeleteFilled />}
            className="table-icon"
            onClick={() => showDeleteConfirm(delFn.bind(null, r.id))}
          >删除</Button> */}
        </div>
      ),
    },
  ];
  columns.map((e) => {
    if (e.dataIndex == 'Index') {
      e.width = '80px';
    } else if (e.dataIndex == 'Operation') {
      e.width = '100px';
    } else {
      e.width = '130px';
    }
  });

  const checkLink = (id) => {
    history.push({
      pathname: '/networkInfor/safetyInspection/checkInspect',
      query: { id },
    });
  };
  const setDisposeLink = (id) => {
    history.push({
      pathname: '/networkInfor/safetyInspection/setDispose',
      query: { id },
    });
  };

  return (
    <>
      <div className="assets_menu">
        <div
          style={{
            width: '15%',
            marginRight: '10px',
            overflow: 'auto',
            height: '100%',
          }}
        >
          <div className="tree_Title">
            <span>筛选器</span>
            <Button
              type="primary"
              danger
              disabled={checkedKeys.length == 0 ? true : false}
              onClick={clearChecked}
            >
              清除
            </Button>
          </div>
          <Tree
            treeData={treeData}
            multiple={false}
            checkable
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            blockNode={true}
            autoExpandParent={autoExpandParent}
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            selectedKeys={selectedKeys}
            title="筛选器"
            style={{
              borderRadius: 8,
              padding: 6,
            }}
          ></Tree>
        </div>
        <div style={{ width: '85%' }}>
          <SearchList searchList={searchList} initList={searchFn}></SearchList>
          <div className="bgf main-x">
            <Table
              columns={columns}
              rowKey="id"
              dataSource={list}
              onChange={changeTable}
              className="custom-table"
              pagination={pagination}
            ></Table>
          </div>
        </div>
      </div>
    </>
  );
};

export default safetyInspection;
